<?php

namespace App\Modules\Admin\Services\Equipment;

use App\Exceptions\Exception;
use App\Library\Junda\src\EquipmentService;
use App\Modules\Admin\Entities\Equipment\EquipmentParamsFreeModel;
use App\Modules\Admin\Entities\Equipment\EquipmentParamsPurifyModel;
use App\Modules\Admin\Entities\Equipment\EquipmentParamsSealModel;
use App\Modules\Admin\Entities\Water\WaterDeviceModel;
use App\Modules\Admin\Services\BaseService;
use Illuminate\Support\Facades\DB;

class EquipmentParamsService extends BaseService
{

    public function __construct(EquipmentParamsFreeModel $apparatus)
    {
        $this->model = $apparatus;
        $this->waterDeviceModel = new WaterDeviceModel();
        $this->freeModel = new EquipmentParamsFreeModel();
        $this->sealModel = new EquipmentParamsSealModel();
        $this->purifyModel = new EquipmentParamsPurifyModel();
        $this->with = ['water_device_info'];
    }


    public function updateParam($params)
    {
        $free_datas = $params['free_data'];
        $purify_datas = $params['purify_data'];
        $seal_datas = $params['seal_data'];
        DB::beginTransaction();
        try {
            $free_arr = [];
            foreach ($free_datas as $free_data) {
                $free_arr[$free_data['ttype']] = $free_data;
                $free_data['operator_name'] = auth('admin')->user()->admin_name;
                unset($free_data['created_time']);
                unset($free_data['updated_time']);
                $this->freeModel->where(['id'=>$free_data['id']])->update($free_data);
            }
            $res_free = $this->OneTweFeeLists($free_arr);
            [$one_success,$two_success] = $res_free;
            if (!$one_success) {
                DB::rollBack();
                throw new Exception('骏达修改失败[费率T1802]');
            }
            if (!$two_success) {
                DB::rollBack();
                throw new Exception('骏达修改失败[费率T1801]');
            }

            foreach ($seal_datas as $seal_data) {
                $seal_success = $this->updateSealDatas($seal_data);
                if (!$seal_success) {
                    DB::rollBack();
                    throw new Exception('骏达修改失败[售水]');
                }
                unset($seal_data['created_time']);
                unset($seal_data['updated_time']);
                $seal_data['operator_name'] = auth('admin')->user()->admin_name;
                $this->sealModel->where(['id'=>$seal_data['id']])->update($seal_data);
            }
            foreach ($purify_datas as $purify_data) {
                $purify_success = $this->updatePurifyDatas($purify_data);
                if (!$purify_success) {
                    DB::rollBack();
                    throw new Exception('骏达修改失败【治水】');
                }
                unset($purify_data['created_time']);
                unset($purify_data['updated_time']);
                $purify_data['operator_name'] = auth('admin')->user()->admin_name;
                $this->purifyModel->where(['id' => $purify_data['id']])->update($purify_data);
            }
            // 缓存
            $this->waterDeviceModel->getCache();
            DB::commit();
            return true;
        } catch (Exception $e) {
            DB::rollBack();
            throw new Exception($e->getMessage());
        }

    }

    /**
     *  处理骏达 设备 费率数据 【保存】
     * @param $free_arr
     * @return array
     */
    protected function OneTweFeeLists($free_arr)
    {
        $one_data = $free_arr[1];
        $two_data = $free_arr[2];
        $three_data = $free_arr[3];
        $junda_insert = [
            'Id' => $one_data['jdfree_id'],
            'EquipmentID' => $one_data['equipment_id'],
            'Etype' => $one_data['type'],
            'Chartype' => $one_data['chartype'],
            'Lpersec' => $one_data['persec'],
            'Lperpul' => $one_data['perpul'],
            'OPrecharge' => $one_data['money'] * 100,
            'Omoney' => $one_data['money'] * 100,
            'GueFee' => $one_data['guefee'],
            'Oquantity' => $one_data['quantity'],
            'TChartype' => $two_data['precharge'],
            'TChartype' => $two_data['chartype'],
            'TLpersec' => $two_data['persec'],
            'TLperpul' => $two_data['perpul'],
            'TPrecharge' => $two_data['money'] * 100,
            'Tmoney' => $two_data['money'] * 100,
            'TGueFee' => $two_data['guefee'],
            'Tquantity' => $two_data['quantity']
        ];

        $OneFeeList = EquipmentService::SaveEquipmentFeeParam($junda_insert);

        $junda_fuqing_insert = [
            'Id' => $three_data['jdfree_id'],
            'EquipmentID' => $three_data['equipment_id'],
            'Etype' => $three_data['type'],
            'OPrecharge' => $three_data['money'] * 100,
            'Chartype' => $three_data['chartype'],
            'Lpersec' => $three_data['persec'],
            'Lperpul' => $three_data['perpul'],
            'Omoney' => $three_data['money'] * 100,
            'GueFee' => $three_data['guefee'],
            'Oquantity' => $three_data['quantity'],
        ];
        $threeFeeList = EquipmentService::SaveEquipmentFeeParam($junda_fuqing_insert);

        return [$OneFeeList['success'], $threeFeeList['success']];
    }

    /**
     *  骏达设备【售水参数 -- 保存】
     * @param $params
     * @return mixed
     */
    protected function updateSealDatas($params)
    {
        $dataSeal = [
            'Id' => $params['jdseal_id'],
            'EquipmentID' => $params['equipment_id'],
            'Ccount' => $params['Ccount'],
            'Flow' => $params['Flow'],
            'Seletor' => $params['Seletor'],
            'Crecycle' => $params['Crecycle'],
            'Lampdelay' => $params['Lampdelay'],
            'Lcokdelay' => $params['Lcokdelay'],
            'MaxSpan' => $params['MaxSpan'],
        ];
        $OneFeeList = EquipmentService::SaveEquipmentSealWaterParam($dataSeal);
        return $OneFeeList['success'];
    }

    /**
     *  骏达设备【制水参数 -- 保存】
     * @param $params
     * @return mixed
     */
    protected function updatePurifyDatas($params)
    {
        $dataPurify = [
            'Id' => $params['jdpurify_id'],
            'EquipmentID' => $params['equipment_id'],
            'Aend' => $params['Aend'],
            'Astart' => $params['Astart'],
            'Hlower' => $params['Hlower'],
            'Hupper' => $params['Hupper'],
            'Pumpspan' => $params['Pumpspan'],
            'auxHeatMode' => $params['auxHeatMode']
        ];
        $OneFeeList = EquipmentService::SaveEquipmentSealWaterParam($dataPurify);
        return $OneFeeList['success'];
    }


    /**
     *  费率参数
     *  售水参数
     *  制水参数
     * @param $params
     * @return void
     */
    public function getSelectListByParams($params)
    {
        $water_id = $params['water_id'];
        $detailApparatus = $this->waterDeviceModel->detail($water_id, '*', false);
        $equipment_id = $detailApparatus['equipment_id'];
        $equipment_id_rich = $detailApparatus['equipment_id_rich'];
        $rest['FreeParamsData'] = $this->getFreeParamsList($detailApparatus, $equipment_id, $equipment_id_rich);
        $rest['SealParamData'] = $this->getSealParamsList($detailApparatus, $equipment_id, $equipment_id_rich);
        $rest['PurifyParamData'] = $this->getPurifyParamsList($detailApparatus, $equipment_id, $equipment_id_rich);
        return $rest;
    }

    /**
     *  费率参数（ 骏达 )
     * @param $detail
     * @param $equipment_id
     * @param $equipment_id_rich
     * @return array[]
     */
    public function getFreeParamsList($detail, $equipment_id, $equipment_id_rich)
    {
        $water_id = $detail['water_id'];
        $OneFeeList = EquipmentService::GetEquipmentFeeParam($equipment_id);

        $OneFeeListRich = EquipmentService::GetEquipmentFeeParam($equipment_id_rich);
//        exit(json_encode([$OneFeeList,$OneFeeListRich]));

        $detailMineral = $OneFeeList['data'];
        $detailRich = $OneFeeListRich['data'];
        $equipment_free = [
            [
                'water_id' => $water_id,
                'title' => "直饮水",
                'ttype' => 1,
                'water_title' => $detail['mineral_title'].'-直饮水',
                'equipment_id' => $detailMineral['EquipmentID'],
                'type' => $detailMineral['Etype'],
                'precharge' => $detailMineral['OPrecharge'],
                'chartype' => $detailMineral['Chartype'],
                'persec' => $detailMineral['Lpersec'],
                'perpul' => $detailMineral['Lperpul'],
                'money' => $detailMineral['Omoney'] / 100,
                'guefee' => $detailMineral['GueFee'],
                'quantity' => $detailMineral['Oquantity'],
                'jdfree_id' => $detailMineral['Id'],
                'QRcode' => $detailMineral['Id'],
                'QRcode' => "https://wxopen.grzq.xyz/api/apicrzs/gq/source?eid={$water_id}&type=1",
                'operator_name' => auth('admin')->user()->admin_name
            ],
            [
                'water_id' => $water_id,
                'title' => "矿化水",
                'ttype' => 2,
                'water_title' => $detail['mineral_title'].'-矿化水',
                'equipment_id' => $detailMineral['EquipmentID'],
                'type' => $detailMineral['Etype'],
                'precharge' => $detailMineral['TChartype'],
                'chartype' => $detailMineral['TChartype'],
                'persec' => $detailMineral['TLpersec'],
                'perpul' => $detailMineral['TLperpul'],
                'money' => $detailMineral['Tmoney'] / 100,
                'guefee' => $detailMineral['TGueFee'],
                'quantity' => $detailMineral['Tquantity'],
                'jdfree_id' => $detailMineral['Id'],
                'QRcode' => "https://wxopen.grzq.xyz/api/apicrzs/gq/source?eid={$water_id}&type=2",
                'operator_name' => auth('admin')->user()->admin_name

            ],
            [
                'water_id' => $water_id,
                'title' => '富氢水',
                'ttype' => 3,
                'water_title' => $detail['rich_title'],
                'equipment_id' => $detailRich['EquipmentID'],
                'type' => $detailRich['Etype'],
                'precharge' => $detailRich['OPrecharge'],
                'chartype' => $detailRich['Chartype'],
                'persec' => $detailRich['Lpersec'],
                'perpul' => $detailRich['Lperpul'],
                'money' => $detailRich['Omoney'] / 100,
                'guefee' => $detailRich['GueFee'],
                'quantity' => $detailRich['Oquantity'],
                'jdfree_id' => $detailRich['Id'],
                'QRcode' => "https://wxopen.grzq.xyz/api/apicrzs/gq/source?eid={$water_id}&type=3",
                'operator_name' => auth('admin')->user()->admin_name
            ],
        ];
        EquipmentParamsFreeModel::getInstance()->where(['water_id' => $water_id])->update(['is_delete' => 1]);

        $equipment_data = [];
        foreach ($equipment_free as $item) {
            $equipment_data[]= EquipmentParamsFreeModel::getInstance()->create($item);
        }
        return $equipment_data;
    }

    /**
     * 售水参数查询
     * @param $detail
     * @param $equipment_id
     * @param $equipment_id_rich
     * @return array[]
     */
    protected function getSealParamsList($detail, $equipment_id, $equipment_id_rich)
    {
        $OneFeeList = EquipmentService::GetEquipmentSealWaterParam($equipment_id);
        $OneFeeListRich = EquipmentService::GetEquipmentSealWaterParam($equipment_id_rich);
        $detailMineral = $OneFeeList['data'];
        $detailRich = $OneFeeListRich['data'];
        $equipment_seal = [
            [
                'water_id' => $detail['water_id'],
                'water_title' => $detail['mineral_title'],
                'equipment_id' => $detailMineral['EquipmentID'],
                'Ccount' => $detailMineral['Ccount'],
                'Crecycle' => $detailMineral['Crecycle'],
                'Seletor' => $detailMineral['Seletor'],
                'Lampdelay' => $detailMineral['Lampdelay'],
                'Lcokdelay' => $detailMineral['Lcokdelay'],
                'MaxSpan' => $detailMineral['MaxSpan'],
                'Flow' => $detailMineral['Flow'],
                'jdseal_id' => $detailMineral['Id'],
                'operator_name' => auth('admin')->user()->admin_name
            ],
            [
                'water_id' => $detail['water_id'],
                'water_title' => $detail['rich_title'],
                'equipment_id' => $detailRich['EquipmentID'],
                'Ccount' => $detailRich['Ccount'],
                'Crecycle' => $detailRich['Crecycle'],
                'Seletor' => $detailRich['Seletor'],
                'Lampdelay' => $detailRich['Lampdelay'],
                'Lcokdelay' => $detailRich['Lcokdelay'],
                'MaxSpan' => $detailRich['MaxSpan'],
                'Flow' => $detailRich['Flow'],
                'jdseal_id' => $detailRich['Id'],
                'operator_name' => auth('admin')->user()->admin_name
            ]
        ];

        EquipmentParamsSealModel::getInstance()->where(['water_id' => $detail['water_id']])
            ->delete();
        $equipment_data = [];
        foreach ($equipment_seal as $item) {
            $equipment_data[] = EquipmentParamsSealModel::getInstance()->create($item);
        }
        return $equipment_data;
    }

    /**
     * 制水参数查询、护膜参数查询、节水参数查询
     * @param $detail
     * @param $equipment_id
     * @param $equipment_id_rich
     * @return array[]
     */
    protected function getPurifyParamsList($detail, $equipment_id, $equipment_id_rich)
    {
        $OnePurifyList = EquipmentService::GetEquipmentPurifyWaterParam($equipment_id);
        $OnePurifyListRich = EquipmentService::GetEquipmentPurifyWaterParam($equipment_id_rich);
        $detailMineral = $OnePurifyList['data'];
        $detailRich = $OnePurifyListRich['data'];
        $equipment_purify = [
            [
                'water_id' => $detail['water_id'],
                'water_title' => $detail['mineral_title'],
                'equipment_id' => $detailMineral['EquipmentID'],
                'Hlower' => $detailMineral['Hlower'],
                'Hupper' => $detailMineral['Hupper'],
                'Astart' => $detailMineral['Astart'],
                'Aend' => $detailMineral['Aend'],
                'Pumpspan' => $detailMineral['Pumpspan'],
                'auxHeatMode' => $detailMineral['auxHeatMode'],
                'jdpurify_id' => $detailMineral['Id'],
                'operator_name' => auth('admin')->user()->admin_name
            ],
            [
                'water_id' => $detail['water_id'],
                'water_title' => $detail['rich_title'],
                'equipment_id' => $detailRich['EquipmentID'],
                'Hlower' => $detailRich['Hlower'],
                'Hupper' => $detailRich['Hupper'],
                'Astart' => $detailRich['Astart'],
                'Aend' => $detailRich['Aend'],
                'Pumpspan' => $detailRich['Pumpspan'],
                'auxHeatMode' => $detailRich['auxHeatMode'],
                'jdpurify_id' => $detailRich['Id'],
                'operator_name' => auth('admin')->user()->admin_name
            ]
        ];
        EquipmentParamsPurifyModel::getInstance()->where(['water_id' => $detail['water_id']])->delete();
        $equipment_data=[];
        foreach ($equipment_purify as $item) {
            $equipment_data[] = EquipmentParamsPurifyModel::getInstance()->create($item);
        }
        return $equipment_data;
    }
}
